//
//  CarCalendarQueryViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-5-31.
//  Copyright (c) 2013年 glendale. All rights reserved.
//
//车厉查询

#import "CarCalendarQueryViewController.h"
#import "MainMenuDataModel.h"
#import "MyAFNetWorkManager.h"
#import "PhotoListViewController.h"
#import "PhotoModel.h"
#import "mm_picRecodeDataModel.h"

@interface CarCalendarQueryViewController ()<RepairCarCheckViewDelegate>

//添加控件
-(void)createSegment;

@property(nonatomic,weak)UIView * currentSubViewIns;
@property(nonatomic,strong) CarReceptionView *carReceptionViewIns;
@property(nonatomic,strong) RepairEstimateView *repairEstimateViewIns;
@property(nonatomic,strong) RepairItemListView *repairItemListViewIns;
@property(nonatomic,strong) UsePartView *usePartViewIns;
@property(nonatomic,strong) OtherChargeList *otherChargeListIns;
@property(nonatomic,strong) ProcessingPlant *processingPlantIns;
@property(nonatomic,strong) SettlementCountView *settlementCountViewIns;
@property(nonatomic,strong) RepairCarCheckView *repairCarCheckViewIns;

@property(nonatomic,weak)IBOutlet UILabel *jobSheet;
@property(nonatomic,weak)IBOutlet UILabel *currentRepairState;

@property(nonatomic,strong)NSMutableDictionary *statusDic;
/** 当前页码 */
@property(nonatomic,assign)int currentIndex;
@property(nonatomic,strong)NSMutableDictionary *queriedData;
@property (weak, nonatomic) IBOutlet UILabel *pageLbl;

@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (weak, nonatomic) IBOutlet UIButton *preBtn;

//some button callBack method
- (IBAction)thePreOrderBtnPressed:(UIButton *)sender;
- (IBAction)theNextOrderBtnPressed:(UIButton *)sender;
- (IBAction)theFirstOrderBtnPressed:(UIButton *)sender;
- (IBAction)theLastOrderBtnPressed:(UIButton *)sender;

@end

@implementation CarCalendarQueryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.currentIndex = 0;
    
    [self addAllObserver];
    
    [self createSegment];
    
    [segmentButton setSelectedSegmentIndex:0];
    
    //创建 sub UIView，并设置初始化默认显示的subView
    rectForSubView = CGRectMake(43, 214, 948, 464);
    
    self.repairItemListViewIns.hidden = NO;
    self.currentSubViewIns = self.repairItemListViewIns;
    
    //将车辆接待作为第一次默认显示的视图
    [self.view addSubview:self.repairItemListViewIns];

    [self setEnableForBtn];
    NSString *roNo = [self getRoNoByIndex:0];
    [self getJobSheetByRoNo:roNo];
}

-(NSString *)getRoNoByIndex:(int)index{
    NSDictionary *dic = self.allHistory[index];
    return dic[@"JOB_SHEET_ID"];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self removeAllObserver];
}


-(void)createSegment
{
    NSArray *segmentArray = [[NSArray alloc] initWithObjects:
                             @"修理项目",
                             @"使用零件",
                             @"附加项目",
                             @"结算统计",
                              nil];
    segmentButton = [[UISegmentedControl alloc] initWithItems:segmentArray];
    CGRect segBtnRect = CGRectMake(42, 170, 948, 44);
    [segmentButton setFrame:segBtnRect];
    [segmentButton setMomentary:NO];
    [segmentButton setSegmentedControlStyle:UISegmentedControlStyleBar];
    [segmentButton setTintColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1]];
    [segmentButton setHighlighted:YES];
    UIImage *img = [UIImage imageNamed:@"mm_red_btn.png"];
    [segmentButton setBackgroundImage:img forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    [segmentButton setBackgroundImage:[UIImage imageNamed:@"mm_gray_btn.png"] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    
    [segmentButton addTarget:self action:@selector(segmentButtonPressed:) forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:segmentButton];
}

-(void)segmentButtonPressed:(id)sender
{
    NSInteger selectedSegment = segmentButton.selectedSegmentIndex;
//    NSLog(@"segment %i selected",selectedSegment);
    
    //更新数据
//    [[MainMenuDataModel sharedMainMenuDataModel] jsonParseFromCarCalendarQueryFile];
    
    //控制车历查询的子视图切换
    switch (selectedSegment)
    {

        case 0:
            [self switchToView:self.repairItemListViewIns];//修理项目
            break;
        case 1:
            [self switchToView:self.usePartViewIns];//使用零件
            break;
        case 2:
            [self switchToView:self.otherChargeListIns];//其他费用
            break;

        case 3:
            [self switchToView:self.settlementCountViewIns];//结算统计
            break;
        case 4:
            [self switchToView:self.repairCarCheckViewIns];//车辆检查
            break;
            
        default:
            break;
    }
    
}

#pragma mark - switch to subViews

-(void)switchToView:(UIView *)view{
    self.currentSubViewIns.hidden = YES;
    view.hidden = NO;
    self.currentSubViewIns = view;
}


- (IBAction)backBtnPressed:(UIButton *)sender
{
//    NSLog(@"backBtnPressed !!!");
    
    [self removeAllObserver];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - some button callBack method

/*
 按钮动作的响应：
 (1)请求数据（新的json数据），然后进行json解析，更新model里边的数据。
 (2)刷新当前选中的segment对应的subView,(即 currentSubViewIns)
 */

- (IBAction)thePreOrderBtnPressed:(UIButton *)sender
{
    --self.currentIndex;
    [self setEnableForBtn];
    NSString *roNo = [self getRoNoByIndex:self.currentIndex];
    [self getJobSheetByRoNo:roNo];
}

- (IBAction)theNextOrderBtnPressed:(UIButton *)sender
{
    ++self.currentIndex;
   [self setEnableForBtn];
    NSString *roNo = [self getRoNoByIndex:self.currentIndex];
    [self getJobSheetByRoNo:roNo];
}

-(void)setEnableForBtn{
    if (self.currentIndex<=0) {
        self.preBtn.enabled = NO;
    }else{
        self.preBtn.enabled = YES;
    }
    
    if (self.currentIndex>=self.allHistory.count-1) {
        self.nextBtn.enabled = NO;
    }else{
        self.nextBtn.enabled = YES;
    }
    
    self.pageLbl.text = [NSString stringWithFormat:@"%d/%d",self.currentIndex+1,self.allHistory.count];
}

- (IBAction)theFirstOrderBtnPressed:(UIButton *)sender
{
    self.currentIndex = 0;
    [self setEnableForBtn];
    NSString *roNo = [self getRoNoByIndex:self.currentIndex];
    [self getJobSheetByRoNo:roNo];
}

- (IBAction)theLastOrderBtnPressed:(UIButton *)sender
{
    self.currentIndex = self.allHistory.count - 1;
    [self setEnableForBtn];
    NSString *roNo = [self getRoNoByIndex:self.currentIndex];
    [self getJobSheetByRoNo:roNo];
}


//注册消息
-(void)addAllObserver
{

}

//移除消息
-(void)removeAllObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 懒加载
-(RepairItemListView *)repairItemListViewIns{
    if (_repairItemListViewIns == nil) {
        _repairItemListViewIns = [[RepairItemListView alloc] initWithFrame:rectForSubView];
        _repairItemListViewIns.backgroundColor = [UIColor whiteColor];
        _repairItemListViewIns.hidden = YES;
        [self.view addSubview:_repairItemListViewIns];
    }
    return _repairItemListViewIns;
}

-(UsePartView *)usePartViewIns{
    if (_usePartViewIns == nil) {
        _usePartViewIns = [[UsePartView alloc] initWithFrame:rectForSubView];
        _usePartViewIns.backgroundColor = [UIColor whiteColor];
        _usePartViewIns.hidden = YES;
        [self.view addSubview:_usePartViewIns];
    }
    return _usePartViewIns;
}

-(OtherChargeList *)otherChargeListIns{
    if (_otherChargeListIns == nil) {
        _otherChargeListIns = [[OtherChargeList alloc] initWithFrame:rectForSubView];
        _otherChargeListIns.backgroundColor = [UIColor whiteColor];
        _otherChargeListIns.hidden = YES;
        [self.view addSubview:_otherChargeListIns];
    }
    return _otherChargeListIns;
}

-(SettlementCountView *)settlementCountViewIns{
    if (_settlementCountViewIns == nil) {
        _settlementCountViewIns = [[SettlementCountView alloc] initWithFrame:rectForSubView];
//        _settlementCountViewIns.backgroundColor = [UIColor whiteColor];
        _settlementCountViewIns.hidden = YES;
        [self.view addSubview:_settlementCountViewIns];
    }
    return _settlementCountViewIns;
}

-(RepairCarCheckView *)repairCarCheckViewIns{
    if (_repairCarCheckViewIns == nil) {
        _repairCarCheckViewIns = [[RepairCarCheckView alloc] initWithFrame:rectForSubView];
        _repairCarCheckViewIns.backgroundColor = [UIColor whiteColor];
        _repairCarCheckViewIns.hidden = YES;
        _repairCarCheckViewIns.RepairCarCheckDelegate = self;
        [self.view addSubview:_repairCarCheckViewIns];
    }
    return _repairCarCheckViewIns;
}

#pragma mark - 获取数据
-(void)getJobSheetByRoNo:(NSString *)roNO{
    
    NSDictionary *obj = self.queriedData[roNO];
    if (obj) {//如果有存储
        [self setDataForViews:obj];
    }else{
        NSDictionary *param = @{@"RO_NO":roNO};
        
        [SVProgressHUD showWithStatus:@"请等待...."];
        //查询工单
        
        [MyAFNetWorkManager postWithParam:param andAction:@"QUERY_REPAIR_ORDER_DETAIL_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
            [SVProgressHUD dismiss];
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"获取数据失败"];
                return;
            }else{
                [self setDataForViews:obj];
                [self.queriedData setObject:obj forKey:roNO];
            }
            
        }];
    }

}

#pragma mark - RepairCarCheckViewDelegate
-(void)viewPictureBtnClicked{
    NSArray *fileList = self.repairCarCheckViewIns.dataDic[@"fileList"];
    if (fileList.count>0) {
        mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];
        picDataModel.arrForAllCapturePic = nil;//清空
        //加入新图片
        picDataModel.arrForAllCapturePic = [NSMutableArray arrayWithArray:picDataModel.arrForNewImage];
        for (NSDictionary *dic in fileList) {//从数据库获取的图片列表
            if (![self Arr:picDataModel.arrForDeletedImages containsObjec:dic]) {
                PhotoModel *pm = [PhotoModel photoModelWithDic:dic];
                [picDataModel.arrForAllCapturePic addObject:pm];
            }
        }
    }
    PhotoListViewController *vc = [[PhotoListViewController alloc]init];
    vc.editOperation = NO;
    [self.navigationController pushViewController:vc animated:YES];
}

-(BOOL)Arr:(NSArray *)arr containsObjec:(NSDictionary *)dic{
    for (NSDictionary *delectedDic in arr) {
        NSString *itemId = [dic[deletedImageName]stringValue];
        if ([delectedDic[deletedImageName] isEqualToString:itemId]) {
            return true;
        }
    }
    return false;
}

-(void)setDataForViews:(NSDictionary *)obj{
    //            NSMutableArray *arr = obj[@"TM_VEHICLE"];//预交款
    //            NSDictionary *predic = arr[0];
    NSMutableDictionary *baseInfo = obj[@"TT_REPAIR_ORDER"][0];//基本信息
    [baseInfo setObject:@(0) forKey:@"PRE_PAY"];
    [self setBaseInfoWithDic:baseInfo];
    self.repairItemListViewIns.repairItemDic = obj[@"TT_RO_LABOUR"];//维修项目
    self.usePartViewIns.usePartDic = obj[@"TT_RO_REPAIR_PART"];//零件
    self.otherChargeListIns.otherChargeDic = obj[@"TT_RO_ADD_ITEM"];//附加项目
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:baseInfo?baseInfo:@{} forKey:@"baseInfo"];//基本信息
    if (obj[@"TT_DEFECT"]) {
        [dataDic setObject:obj[@"TT_DEFECT"] forKey:@"defectList"];//缺陷
    }
    if (obj[@"TT_RO_CONFIRM"]) {
        [dataDic setObject:obj[@"TT_RO_CONFIRM"] forKey:@"goodsConfirm"];//物品确认
    }
    if (obj[@"TT_RO_FILE"]) {
        [dataDic setObject:obj[@"TT_RO_FILE"] forKey:@"fileList"];//图片列表
    }
    self.repairCarCheckViewIns.dataDic = dataDic;
    self.settlementCountViewIns.jobSheetData = obj;
    [self.currentSubViewIns setNeedsDisplay];
}

-(void)setBaseInfoWithDic:(NSDictionary *)dic{
    self.jobSheet.text = dic[@"RO_NO"];
    self.currentRepairState.text = self.statusDic[[dic[@"RO_STATUS"]stringValue]];
}

-(NSMutableDictionary *)queriedData{
    if (_queriedData == nil) {
        _queriedData = [NSMutableDictionary dictionary];
    }
    return _queriedData;
}

-(NSMutableDictionary *)statusDic{
    if (_statusDic == nil) {
        _statusDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_RO_STATUS"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_statusDic setObject:name forKey:val];
        }
    }
    return _statusDic;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

@end
